package com.system

import grails.converters.JSON
import grails.transaction.Transactional

class UploadController {

    def index() {

    }

    @Transactional
    def upload() {

        def info = [result:false,msg: "文件上传失败！"]

        try {

            def file = request.getFile("file")

            //原文件名
            String oldName = file.getOriginalFilename()

            //用时间戳作为新文件名
            String newName = System.currentTimeMillis()+oldName.substring(oldName.lastIndexOf(".",oldName.length()-1))

            //文件保存相对路径
            String path = "/upload"

            //文件保存绝对路径
            String dirPath = request.getSession().getServletContext().getRealPath(path)

            File saveFile = new File(dirPath)
            if(!saveFile.exists()){
                saveFile.mkdirs()
            }
            if(file){
                //上传文件
                file.transferTo(new File(dirPath + File.separator + newName))
                //文件上传成功后，文件信息录入文件信息表
                FileResource fr = new FileResource(oldName,newName,path,dirPath)
                fr.save(failOnError:true,flash:true)
                info.result = true
                info.msg = "文件上传成功！"
                info.uuid = fr.uuid
            }
        } catch (e) {
            log.error("文件上传失败，errorMsg={}",e)
        }
        //返回json
        render info as JSON
    }
}
